import React, { Component } from 'react'
import './css/04-indec.css'
export default class App extends Component {
  myInput = React.createRef()
  state = {
    list: [{id: 1, value: '111'}]
  }
  render() {
    return (
      <div>
        <input ref={this.myInput}></input>
        <button onClick={() => {this.handleAdd()}}>添加</button>
        <ul>
          { 
            this.state.list.map((item, index) =>
              <li key={item.id}>
                {/* {item.value} */}
                {/* 富文本 如果输入<h1>标题</h1>这种带标签的会自动解析成html*/}
                <b dangerouslySetInnerHTML={
                    {
                        __html: item.value
                    }
                }></b>
                <button onClick={() => {this.handleDel(index)}}>删除</button>
              </li>
            )
          }
        </ul>
        {/* 条件判断 */}
        {/* { !this.state.list.length ? <p>暂无数据</p> : null } */}
        {/* { !this.state.list.length && <p>暂无数据</p> } */}
        <p className={this.state.list.length === 0 ? '' : 'hidden'}>暂无数据</p>
      </div>
    )
  }
  handleAdd() {
    const value = this.myInput.current.value
    // 不要修改原状态
    // let newList = [...this.state.list] 与 this.state.list.slice() 与 this.state.list.concat() 等价
    let newList = [...this.state.list]
    newList.push({id: Math.random()*1000, value})
    // setState及时更新页面数据
    this.setState({
      list: newList
    })
    this.myInput.current.value = ''
    console.log(this.myInput.current.value);
  }
  handleDel(index) {
    let newList = this.state.list.concat()
    newList.splice(index, 1)
    this.setState({
      list: newList
    })
  }
}
